// 公共hooks
import { message } from 'antd';
import axios from 'axios'
import {useEffect, useState} from 'react'
function usePublish(type){
    const [dataSource,setDataSource]=useState([]);
    const {username}=JSON.parse(localStorage.getItem("token"))
    // 根据接受的type获取不同状态的新闻
    useEffect(() => {
        axios.get(`/news?author=${username}&publishState=${type}&_expand=category`).then(res=>{
            // console.log(res.data);
            setDataSource(res.data)
        })

    }, [username,type])

    // 发布新闻方法
    const handlePublish=(id)=>{
        setDataSource(dataSource.filter(item=>item.id!==id))
        axios.patch(`/news/${id}`, {
            "publishState": 2,
            "publishTime":Date.now()
        }).then(res=>{
            message.success('您可以在发布管理/已发布中查看您的新闻')
        })
    }

    // 下线新闻
    const handleSunset=(id)=>{
        setDataSource(dataSource.filter(item=>item.id!==id))
        axios.patch(`/news/${id}`, {
            "publishState": 3,
        }).then(res=>{
            message.success('您可以在发布管理/已下线中查看您的新闻')
        })
    }

    // 删除新闻
    const handleDelete=(id)=>{
        setDataSource(dataSource.filter(item=>item.id!==id))
        axios.delete(`/news/${id}`).then(res=>{
            message.warn('您已经删除了已下线的新闻')
        })
    }
    return{
        dataSource,
        handleDelete,
        handlePublish,
        handleSunset
    }
}

export default usePublish